const {
	tagModel
} = require('../models/tag.model')

module.exports = class Tag {

	//增加标签
	static async addTag(ctx) {
		let {
			title
		} = ctx.request.body
		if (!title) {
			return ctx.fail({
				msg: '缺少必填项'
			})
		}
		const author = ctx.user;
		const newTag = new tagModel({
			title,
			author: author.id
		})
		await newTag.save()
		return ctx.success({
			msg: '新增成功',
			data: newTag.toJSONFor()
		})
	}

	//删除标签
	static async deleteTag(ctx) {
		let {
			id
		} = ctx.request.body
		if (!id) {
			return ctx.fail({
				msg: '缺少必填项'
			})
		}
		const res = await tagModel.remove({
			_id: id
		});
		if (res.ok == 1) {
			return ctx.success({
				msg: '删除成功'
			})
		}
	}

	//更改标签
	static async updateTag(ctx) {

		const newTag = ctx.request.body;

		if (!(newTag.id || newTag.title)) {
			return ctx.fail({
				msg: '缺少必填项'
			})
		}
		const tag = await tagModel.findById(newTag.id);

		if (newTag.title != undefined) {
			tag.title = newTag.title;
		}
		await tag.save();
		return ctx.success({
			msg: '修改成功',
			data: tag
		})
	}

	//查询所有标签
	static async allTag(ctx) {
		let page = 1;
		let size = 10

		let query = {}
		let tags = []

		if (ctx.request.query.size != undefined) {
			size = ctx.request.query.size;
		}

		if (ctx.request.query.page != undefined) {
			page = ctx.request.query.page;
		}

		if (ctx.request.query.userId != undefined) {
			let userId = ctx.request.query.userId;
			query.author = {
				$in: [userId]
			}
		}


		//分页
		tags = await tagModel.find(query)
			.skip(Number(page - 1))
			.limit(Number(page * size))
			.sort({
				creatAt: -1
			})


		return ctx.success({
			msg: '获取成功',
			data: {
				tags,
				total: tags.length
			}
		})
	}

}
